import java.io.RandomAccessFile;
import java.util.HashMap;

public class QueryOnFile{
	
	private static int[] valueLength = {6,10,8,5,5,6,6,5,5,4,7,6,4,3}; 
	
	public static void main(String[] args){
		double info = getAverageTEMP(10015, "03-06-2012", "20");
		System.out.println("The average temperature of the given date an the given hour is " + info);
	}
	
	//Get the average temperature
	private static double getAverageTEMP(int stn, String date, String hour){
		double avgTEMP = 0.0;
		String[] temperatures = new String[15];
		String[] datum = date.split("-");
		String newDate = datum[0] + datum[1] + datum[2];
		
		DatabaseStations database = new DatabaseStations();
		HashMap<Integer, Integer> stations = database.getStations();	
		int index = stations.get(stn);
		
		String path = "Measurements/" + newDate + "/"+ hour + ".txt";		
		
		try {
			RandomAccessFile file = new RandomAccessFile(path, "r");			
			int counter= 0;
			while(counter<15){
								
				file.seek(counter*(83 * 8000) + ((index*83)+22));
				byte[] value = new byte[5];
				for(int i = 0; i<valueLength[3]; i++){
					value[i] = file.readByte();
				}
				
				temperatures[counter] = new String(value);				
				counter++;
			}				
		} catch (Exception e) {	
			e.printStackTrace();
		}		
		
		double total = 0.0;
		double size = 15.0;		
		for(int i = 0; i<15; i++){
			if(!temperatures[i].trim().isEmpty()){
				total += Double.parseDouble(temperatures[i]);
			} else{
				size--;
			}			
		}		
		avgTEMP = Math.round(total / size);
		
		//System.out.println(avgTEMP);
		return avgTEMP;
	}

}